import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "@/store";
import HomeView from '../views/Manage.vue'

const routerPush = VueRouter.prototype.push;

// VueRouter.prototype.push = function (location) {
//
//   return routerPush.call(this, location).catch(err => {})
//
// };
Vue.use(VueRouter)

const routes = [
    {path: '/login', name: 'Login', component: () => import('../views/Login.vue')},
    {path: '/register', name: 'Register', component: () => import('../views/Register.vue')},
    {path: '/404', name: '404', component: () => import('../views/404.vue')},
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

//刷新页面会导致页面路由重置
export const setRoutes = () => {
    const storeMenus = localStorage.getItem("menus");
    if (storeMenus) {
        //拼装动态路由
        const manageRoute = {
            path: '/', name: 'Manage', component: () => import('../views/Manage.vue'),
            redirect: "/login",
            children: [
                {path: '/person', name: 'Person', component: () => import('../views/Person.vue')},
            ]
        }
        const menus = JSON.parse(storeMenus)
        menus.forEach(item => {
            if (item.path) {         //当且仅当path不为空的时候才去设置路由
                let itemMenu = {
                    path: item.path.replace("/", ""),
                    name: item.name,
                    component: () => import('../views/' + item.pagePath + '.vue')
                }
                manageRoute.children.push(itemMenu)
            } else if (item.children.length) {
                item.children.forEach(item => {
                    if (item.path) {
                        let itemMenu = {
                            path: item.path.replace("/", ""),
                            name: item.name,
                            component: () => import('../views/' + item.pagePath + '.vue')
                        }
                        manageRoute.children.push(itemMenu)
                    }
                })
            }
        })

        //获取当前路由对象名称数组
        const currentRouteNames = router.getRoutes().map(v => v.name)
        if (!currentRouteNames.includes('Manage')) {
            //动态添加到现在的路由对象中去
            router.addRoute(manageRoute)
        }
    }
}
//重置就再获取一次路由
setRoutes()


// 解决跳转到当前路由报错问题//重复路由
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

//路由守卫
router.beforeEach((to, from, next) => {
    localStorage.setItem("currentPathName", to.name)//获取当前路由的名称，首页旁边的/路由
    store.commit("setPath")//触发store数据更新

    //未找到路由的情况下 404
    if (!to.matched.length){
        const storeMenus = localStorage.getItem("menus")
        if (storeMenus){
            next("/404")
        }else {
            next("/login")
        }
    }
//其他情况放行
    next()
// to 表示要去哪里
// from 表示来自那个地方
// next 表示是否放行
})

//登录拦截器
router.beforeEach((to, from, next) => {
    //对跳转的页面进行拦截，作用在判断是否登陆/登陆是否过期/有无权限
    //可以分别打印to，from，next看看分别是什么
    //判断条件则需要根据自己的情况定义了
    if (to.path === '/login' || to.path === '/register') {
        next();
    } else {
        let token = localStorage.getItem('user');
        if (token === null || token === '') {
            next('/login');
            console.log("未登录，禁止访问")
        } else {
            next();
        }
    }
})
export default router
